package qky.api.controller.registerlogin;


import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import qky.api.annotation.Login;
import qky.api.controller.BaseController;
import qky.api.entity.FirmEntity;
import qky.api.entity.UserEntity;
import qky.api.form.user.LoginForm;
import qky.api.form.user.RegisterForm;
import qky.api.service.FirmService;
import qky.api.service.TokenService;
import qky.api.service.UserService;
import qky.common.utils.MapParamBuilder;
import qky.common.utils.R;
import qky.common.validator.ValidatorUtils;

@RestController
@RequestMapping("/api/rl")
@Api(tags="登录注册", description="【OK】")
public class ApiLoginController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private FirmService firmService;

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterForm form){
        ValidatorUtils.validateEntity(form);
        UserEntity userEntity = userService.getByMobile(form.getMobile());
        if(userEntity!=null){
            return R.error("此手机号已注册");
        }
        List<FirmEntity> list = firmService.queryList(new MapParamBuilder<String, Object>().param("EQ_firmName", form.getCompany()).get());
        if (!CollectionUtils.isEmpty(list)) {
            return R.error("企业名已注册");
        }

        UserEntity user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setContacts(form.getContacts());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        userService.register(user, form.getCompany());
        return R.ok();
    }

    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);
        Map<String, Object> map = userService.login(form.getMobile(), form.getPassword());
        return R.ok().putData(map);
    }

    @Login
    @PostMapping("logout")
    @ApiOperation(value = "退出", notes = "userId:string")
    public R logout(@RequestBody JSONObject paramJson){
        tokenService.expireToken(paramJson.getString("userId"));
        return R.ok();
    }

}
